package com.campus.customer.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.campus.common.constants.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class WechatService {
	private static final String GET_ACCESS_TOKEN_URL =
			"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";


	@Value(value = "${wechat.appid}")
	private String appid;

	@Value(value = "${wechat.secret}")
	private String secret;


	@Autowired
	private RedisService redisService;


	/**
	 * 获取小程序全局唯一后台接口调用凭据AccessToken
	 * @return
	 */
	public String getAccessToken() {
		String accessTokenInRedis = redisService.get(GlobalConstant.WECHAT_ACCESS_TOKEN + appid);

		if(StringUtils.isNotBlank(accessTokenInRedis)){
			return accessTokenInRedis;
		}

		String url = String.format(GET_ACCESS_TOKEN_URL, appid, secret);
		String result = HttpUtil.get(url, StandardCharsets.UTF_8);

		log.info("获取accessToken接口返回结果：{}", result);

		JSONObject resultJO = JSONUtil.parseObj(result);

		String accessToken = resultJO.getStr("access_token");
		Long expiresIn = resultJO.getLong("expires_in");

		//TODO 保存到redis
		if(StringUtils.isNotBlank(accessToken)){
			redisService.set(GlobalConstant.WECHAT_ACCESS_TOKEN + appid, accessToken, expiresIn-100);
		}

		return accessToken;
	}

}
